package com.cloud.school.app.config.security;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;

/**
 * @ClassName OkHttpUtil
 * @Description TODO
 * @Author 36297
 * @Date 2018/12/10 21:11
 * @Version 1.0
 */
@Slf4j
public class OkHttpUtil {
    private static final OkHttpClient okHttpClient = new OkHttpClient();
    private static final MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");

    /**
     * @Title: sendPostAync
     * @Description: 异步回调post
     * @param url
     * @param param
     * @param responseHandler
     * @return: void
     * @author: pc
     * @date: 2018/9/24 12:28
     */
    public static void sendPostFormAync(String url, String param, ResponseHandler responseHandler) {
        sendPostAync(url, param, mediaType, responseHandler);
    }


    public static void sendPostAync(String url, String param, MediaType mediaType, ResponseHandler responseHandler) {
        log.debug("开始---请求地址:{} ,参数:{}", url, param);
        Request request = new Request.Builder().url(url).post(RequestBody.create(mediaType, param)).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.error("请求出现异常！url{} ,异常原因:{}", url, e.getMessage(), e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseContent = response.body().string();
                    log.debug("结束---请求地址:{} ,返回结果:{}", url, param, responseContent);
                    responseHandler.handle(responseContent);
                } catch (Exception e) {
                    throw new IOException(e.getMessage());
                }
            }
        });
    }

    public static <T> T sendPostForm(String url, String param, TypeReference<T> type) {
        return sendPost(url, param, mediaType, type);
    }

    public static <T> T sendPost(String url, String param, MediaType mediaType, TypeReference<T> type) {
        log.debug("开始---请求地址:{} ,参数:{}", url, param);
        Request request = new Request.Builder().url(url).post(RequestBody.create(mediaType, param)).build();
        String result = null;
        try {
            Response response = okHttpClient.newCall(request).execute();
            result = response.body().string();
            log.debug("结束---请求地址:{} ,返回结果:{}", url, result);
            return JSON.parseObject(result, type);
        } catch (JSONException e) {
            log.error("JSON解析出现异常！请求url{} ,返回值:{}，异常原因:{}", url, result, e.getMessage(), e);
        } catch (Exception e) {
            log.error("请求出现异常！url{} ,异常原因:{}", url, e.getMessage(), e);
        }
        return null;
    }


    public static <T> T sendGet(String url, String param, MediaType mediaType, TypeReference<T> type) {
        log.debug("开始---请求地址:{} ,参数:{}", url, param);
        Request request = new Request.Builder().url(url).build();
        String result = null;
        try {
            Response response = okHttpClient.newCall(request).execute();
            result = response.body().string();
            log.debug("结束---请求地址:{} ,返回结果:{}", url, param, result);
            T resEX = JSON.parseObject(result, type);
            return resEX;
        } catch (JSONException e) {
            log.error("JSON解析出现异常！请求url{} ,返回值:{}，异常原因:{}", url, result, e.getMessage(), e);
        } catch (Exception e) {
            log.error("请求出现异常！url{} ,异常原因:{}", url, e.getMessage(), e);
        }
        return null;
    }

    public interface ResponseHandler {
        /**
         * @Title: handle
         * @Description: 异步回调请求回调函数
         * @param responseBody
         * @return: void
         * @author: pc
         * @date: 2018/9/24 12:30
         */
        void handle(String responseBody);
    }
}
